package com.example.chatty.ui.components

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import com.example.chatty.screens.contracts.Contracts
import com.example.chatty.screens.drawer.PersonalProfile
import com.example.chatty.screens.explorer.Explorer
import com.example.chatty.ui.IMChat.Home
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.rememberPagerState
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class, ExperimentalPagerApi::class)
@Composable
fun AppScaffold() {

    val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
    val pagerState = rememberPagerState()
    val scope = rememberCoroutineScope()
    var selectedScreen by remember {
        mutableStateOf(0)
    }

    ModalNavigationDrawer(
        drawerContent = {
            PersonalProfile()
        },
        drawerState = drawerState,
        modifier = Modifier.navigationBarsPadding()
    ) {
        Scaffold(
            bottomBar = {
                MyBottomNavigation(selectedScreen = selectedScreen, onClick = {
                    scope.launch {
                        pagerState.scrollToPage(it)
                    }
                })
            }
        ) {
            HorizontalPager(
                count = BottomScreen.values().size,
                state = pagerState,
                userScrollEnabled = false,
                contentPadding = it
            ) { page ->
                when (BottomScreen.values()[page]) {
                    BottomScreen.Message -> Home(drawerState = drawerState)
                    BottomScreen.Contract -> Contracts()
                    BottomScreen.Explore -> Explorer()
                }
            }
        }
    }
    LaunchedEffect(key1 = pagerState) {
        snapshotFlow {
            pagerState.currentPage
        }.collect { page ->
            selectedScreen = page
        }
    }

    BackHandler(enabled = drawerState.isOpen) {
        scope.launch {
            drawerState.close()
        }
    }
}